<template>
  <div class="center">
    <div class="city-search">
      <el-input placeholder="请输入SN" v-model="snValue" class="input-with-select" size="small">
        <el-button slot="append" icon="el-icon-search" @click="getLongitudeAndLatitude" style="border-radius: 0 50px 50px 0"></el-button>
      </el-input>
    </div>
    <transition name="el-fade-in-linear">
      <div class="sn-center" v-if="snShow">
        <div class="sn-img"><img src="@/assets/images/pad.png" alt="" /></div>
        <div class="electric flex flex_cen felx_align">
          <battery style="margin-right: 5px" :proQuantity="Number(snData.electric)" proIsColor="#646464" :width="20" :height="5" />{{ snData.electric }}%
        </div>
        <div class="sn-name">
          {{ snData.realname }}  {{ snData.sn }}
        </div>
        <div class="sn-time">
          <div v-if="snData.online" class="flex felx_align flex_cen">
            <i class="iconfont icondian" :class="snData.online ? 'on_line' : ''"></i>{{ snDate }}前定位成功 {{snData.update_time | activateTime}}
          </div>
          <div v-else lass="flex felx_align flex_cen" style="text-align: center">
            <i class="iconfont icondian" :class="snData.online ? 'on_line' : ''"></i>设备已离线
          </div>
        </div>
        <div class="sn-time">
          {{ detailsCity }}
        </div>
        <div class="flex felx_align flex_bet">
          <div class="sn-button">
            <el-button round size="mini" @click="getrefreshEquipParam" :loading="cityLoading" circle><i v-if="!cityLoading" class="iconfont iconcaiji"></i></el-button>
            <div class="city_txt">定位刷新</div>
          </div>
          <div class="sn-icon">
            <el-button round size="mini" circle @click="getissueVoice" :loading="voiceLoading"><i v-if="!voiceLoading" class="iconfont icontongzhi"></i></el-button>
            <div class="city_txt">发出声音</div>
          </div>
        </div>
      </div>
    </transition>
    <div class="map" id="container"></div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import battery from "@/components/electric";
import images from "../../../assets/images/citygd.png";
import citylx from "../../../assets/images/citylx.png";
import { LongitudeAndLatitude, issueVoice } from "@/api/city.js";
import { refreshEquipParam } from "@/api/equipment.js";

export default {
  components: { battery},
  data() {
    return {
      coordinates: [114.12479, 22.682364],
      snValue: "",
      snData: {},
      snDate: "",
      snShow: false,
      cityLoading: false,
      voiceLoading: false,
      time: null,
      detailsCity: ''
    };
  },
  mounted() {
    if (this.$route.query.sn) {
      this.snValue = this.$route.query.sn
      this.pathCity(this.snValue);
    }
    this.initAMap(this.coordinates, 1);
  },
  beforeDestory() {
    clearInterval(this.time);
  },
  methods: {
    //设备信息刷新
    getrefreshEquipParam(sn) {
      this.cityLoading = true;
      let qs = { sn: this.snValue, userId: localStorage.getItem("ID") };
      refreshEquipParam(qs).then((res) => {
        this.time = setTimeout(() => {
          this.getLongitudeAndLatitude(this.snValue);
          this.cityLoading = false;
        }, 9000);
      }).catch((err) => {
        this.cityLoading = false;
      });
    },
    //发送声音
    getissueVoice() {
      this.voiceLoading = true;
      let qs = { sn: this.snValue, userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), };
      issueVoice(qs).then((res) => {
        this.voiceLoading = false;
        this.$message.success(res.msg);
      }).catch((err) => {
        this.voiceLoading = false;
      });
    },
    //sn查询坐标
    getLongitudeAndLatitude(sn) {
      if (this.snValue) {
        if (this.snValue.length < 30) {
          LongitudeAndLatitude({
            userId: localStorage.getItem("ID"),
            sn: this.snValue,
          }).then((res) => {
            if (res.data.longitude != null && res.data.latitude != null) {
              this.snData = res.data;
              let arr = [res.data.longitude, res.data.latitude];
              this.initAMap(arr, res.data.online);
              this.snShow = true;
              var timestamp = new Date().getTime(); //获取当前时间戳
              this.snDate = this.getDaysAndHours(res.data.update_time, timestamp);
            } else {
              this.$message.error("没有定位信息");
            }
          }).catch((err) => {
            this.snShow = false;
            err.code == 400 ? this.$message.error(err.msg) : "";
          });
        } else {
          this.$message.error("请输入正确的SN码");
        }
      } else {
        this.$message.error("请输入SN码");
      }
    },

    initAMap(city, type) {
      window._AMapSecurityConfig = {
        securityJsCode: "c3b09b8de928731bf485d4c1f5a3a006",
      };
      AMapLoader.load({
        key: "3ac8c752c83477244c4e9df3aa54d89c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0",
        plugins: ["Amap.Geocoder", "AMap.Scale"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          let that = this
          var map = new AMap.Map("container", {
            zoom: 15,
            center: city, //中心点坐标
          });
          AMap.plugin("AMap.ToolBar", function () {
            var toolbar = new AMap.ToolBar({
              offset: new AMap.Pixel(25, 80),
            });
            map.addControl(toolbar);
          });
          //自定义icon
          var icon = new AMap.Icon({
            size: new AMap.Size(100, 100), // 图标尺寸
            image: type ? images : citylx, // Icon的图像
            imageSize: new AMap.Size(100, 100), // 根据所设置的大小拉伸或压缩图片
          });
          var arr = new AMap.Marker({
            position: new AMap.LngLat(...city),
            icon: icon,
            offset: new AMap.Pixel(-20, -38),
            // title: '测试'
          });
          //逆地理编码
          AMap.plugin('AMap.Geocoder', function () {
            var geocoder = new AMap.Geocoder()
            var lnglat = city
            geocoder.getAddress(lnglat, function (status, result) {
              if (status === 'complete' && result.info === 'OK') {
                // result为对应的地理位置详细信息
                that.detailsCity = result.regeocode.formattedAddress
                // that.$message.success("定位成功");
              } else {
                that.detailsCity = ''
                that.$message.error('根据经纬度查询地址失败')
              }
            })
          })
          map.add(arr);

        })
        .catch((e) => {
          console.log(e);
        });
    },

    pathCity(sn) {
      LongitudeAndLatitude({
        userId: localStorage.getItem("ID"),
        sn: sn,
      }).then((res) => {
        if (res.data.longitude != null && res.data.latitude != null) {
          this.snData = res.data;
          let arr = [res.data.longitude, res.data.latitude];
          this.initAMap(arr, res.data.online);
          this.snShow = true;
          var timestamp = new Date().getTime(); //获取当前时间戳
          this.snDate = this.getDaysAndHours(res.data.update_time, timestamp);
        } else {
          this.$message.error("没有定位信息");
        }
      }).catch((err) => {
        this.snShow = false;
        err.code == 400 ? this.$message.error(err.msg) : "";
      });
    },
    // 计算两个时间戳之间相差的天数
    getDaysAndHours(time, date) {
      var time1 = new Date(Number(time) * 1000);
      var time2 = new Date(date);
      var timeDiff = time2.getTime() - time1.getTime();
      // timeDiff = 时间戳差值
      let days = Math.floor(timeDiff / (24 * 3600 * 1000)); // 计算出天数
      let leavel1 = timeDiff % (24 * 3600 * 1000); // 计算天数后剩余的时间
      let hours = Math.floor(leavel1 / (3600 * 1000)); // 计算天数后剩余的小时数
      let leavel2 = timeDiff % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
      let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
      return days != 0 ? `${days}天${hours}小时${minutes}分` : `${hours}小时${minutes}分`

    },
    //计算时间差
    tiemDiff(time, date) {
      var time1 = new Date(Number(time) * 1000);
      var time2 = new Date(date);
      var sec = time2.getTime() - time1.getTime();
      var second = 1000,
        minute = 60 * second,
        hour = 60 * minute,
        day = 24 * hour;
      var t = Math.floor(sec / hour) / 24
      var hours = Math.floor(sec / hour);
      sec -= hours * hour;
      var minutes = Math.floor(sec / minute);
      sec -= minutes * minute;
      var seconds = Math.floor(sec / second);
      let times = hours != 0 ? `${hours}小时${minutes}分` : `${minutes}分${seconds}秒`;
      return times;
    },
  },
};
</script>


<style lang="scss" scoped>
.slide-fade-enter-active {
  transition: all 0.2s ease;
}
.slide-fade-leave-active {
  transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1);
}
.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateX(5px);
  opacity: 0;
}
.sn-time {
  font-size: 12px;
  margin: 10px 0;
  text-align: center;
  max-width: 300px;
  line-height: 18px;
}
.center {
  height: 100vh;
  width: 100%;
  padding: 0;
}
.map {
  height: 100%;
  width: 100%;
}
.city-search {
  position: absolute;
  top: 30px;
  left: 2%;
  z-index: 999;
  // width: 15%;
}
.sn-center {
  min-width: 20%;
  position: absolute;
  top: 30px;
  right: 2%;
  z-index: 999;
  background-color: #ffffff;
  padding: 20px 70px;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 10px 0 #b6b5b3;
  .sn-img {
    text-align: center;
    img {
      height: 60px;
      width: 90px;
    }
  }
  button {
    letter-spacing: 1px;
  }
}
.electric {
  font-size: 12px;
  margin: 10px 0;
  color: #646464;
}
.sn-name {
  color: #000000;
  font-weight: 600;
  text-align: center;
  margin: 10px 0;
}
.sn-button {
  margin: 10px 0;
  text-align: center;
}
.sn-icon {
  text-align: center;
  .icon {
    font-size: 32px;
    color: #16a53a;
  }
}
.city_txt {
  font-size: 12px;
  margin-top: 8px;
}
.screen_Txt {
  margin-top: 5px;
}
</style>

